package pc

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"strconv"
	"strings"
	"tcsc/controllers/mobile"
	"tcsc/models"
	"tcsc/sword"
	"time"

	"github.com/360EntSecGroup-Skylar/excelize"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

// "sword"
type IsShopcar struct {
	BaseController
}

func (c *IsShopcar) Get() {
	var isshopcar bool
	shopcar := models.Query(`select id from mt_order_car where type in(0,2) and status=1 and uid=` + c.Uid + ` and pid=` + c.GetString("pid"))
	if shopcar != nil {
		isshopcar = true
	} else {
		isshopcar = false
	}
	if c.IsAjax() {
		var js = make(map[string]interface{})
		js["isshopcar"] = isshopcar
		c.Data["json"] = js
		c.ServeJSON()
	} else {
		c.Data["isshopcar"] = isshopcar
	}
}

type Shopcar struct {
	BaseController
}

func (c *Shopcar) Get() {
	gids := models.Query(`select a.gid from mt_order_car a where a.type in(0,2) and a.status=1 and a.uid=` + c.Uid + ` group by a.gid`)
	for _, v := range gids {
		gid := fmt.Sprint(v["gid"])
		if gid != "0" {
			v["shop"] = models.Query(`select id,name from mt_shop where id=` + gid)[0]
		}
		shopcar := models.Query(`select a.id,a.num,b.title,b.isvip,a.gid,c.pathname,b.model,a.price,b.number,a.pid,a.spec,b.minbuy,b.width,b.height,b.length,b.weight 
			from mt_order_car a 
			left join mt_product b on a.pid=b.id 
			left join mt_resources c on b.img=c.id 
			where a.type in(0,2) and a.status=1 and a.uid=` + c.Uid + ` and a.gid=` + gid)
		now := sword.Gettimes("")
		for _, s := range shopcar {
			gbuy := models.Query(`select min from mt_active_gbuy where end=0 and pid=` + s["pid"].(string) + ` and status=1 and starttime<='` + now + `' and endtime>'` + now + `' 
				order by addtime desc`)
			if gbuy != nil {
				s["min"] = gbuy[0]["min"].(string)
			}
			s["priceone"] = s["price"]
			var pricem float64
			price, _ := strconv.ParseFloat(fmt.Sprint(s["price"]), 64)
			if fmt.Sprint(s["spec"]) == "0" {
				number, _ := strconv.ParseFloat(fmt.Sprint(s["number"]), 64)
				pricem = price * number
			} else {
				pricem = price
			}
			s["price"] = fmt.Sprintf(`%.2f`, price)
			s["pricem"] = fmt.Sprintf(`%.2f`, pricem)
			if iscollect := models.Query(`select id from mt_member_collection where uid=` + c.Uid + ` and pid=` + s["pid"].(string)); iscollect != nil {
				s["iscollect"] = 1
			} else {
				s["iscollect"] = 0
			}
		}
		v["shopcar"] = shopcar
	}
	c.Data["info"] = gids
	c.TplName = "pc/shopcar/index.html"
}
func (c *Shopcar) Post() {
	defer c.ServeJSON()
	if c.Uid == "" {
		c.Data["json"] = 2
	} else {
		pid := c.GetString("pid")
		num := c.GetString("num")
		enough := models.Query(`select id from mt_product where id=? and inventory>=?`, pid, num)
		if enough == nil {
			c.Data["json"] = 3
			return
		}
		spec := "0"
		specg := c.GetString("spec")
		if specg != "" {
			spec = specg
		}
		if ishave := models.Query(`select id from mt_order_car where pid=` + pid + ` and uid=` + c.Uid + ` and status=1 and type<>1 and spec=` + spec); ishave != nil {
			if err := models.Exec(`update mt_order_car set num=num+` + num + ` where id=` + ishave[0]["id"].(string)); err != nil {
				beego.Debug(err)
				c.Data["json"] = 0
			} else {
				c.Data["json"] = 1
			}
		} else {
			price, gid, tid := mobile.ProductPrice(pid, c.Uid)
			pro := models.Query(`select a.id,a.barcode,b.type from mt_product a left join mt_brand b on a.bid=b.id where a.id=` + pid)[0]
			if pro["type"].(string) == "2" {
				pid = models.Query(`select id from mt_product where status=1 and censoring=1 and barcode=` + pro["barcode"].(string) + ` and id!=` + pro["id"].(string))[0]["id"].(string)
			}
			sql := fmt.Sprintf(`insert into mt_order_car (pid,gid,num,uid,price,addtime,spec,type) values (%v,%v,%v,%v,%v,'%v',%v,%v)`,
				pid, gid, num, c.Uid, price, sword.Gettimes(""), spec, tid)
			if err := models.Exec(sql); err != nil {
				beego.Debug(err)
				c.Data["json"] = 0
			} else {
				c.Data["json"] = 1
			}
		}
	}
}

type ShopcarP struct {
	BaseController
}

func (c *ShopcarP) Post() {
	defer c.ServeJSON()
	var js = make(map[string]interface{})
	c.Data["json"] = &js
	if c.Uid == "" {
		js["status"] = 2
	} else {
		spec := "0"
		specg := c.GetString("spec")
		if specg != "" {
			spec = specg
		}
		pid := c.GetString("pid")
		num := c.GetString("num")
		enough := models.Query(`select id from mt_product where id=? and inventory>=?`, pid, num)
		if enough == nil {
			js["status"] = 3
			return
		}
		if ishave := models.Query(`select id from mt_order_car where pid=` + pid + ` and uid=` + c.Uid + ` and status=1 and type<>1 and spec=` + spec); ishave != nil {
			if err := models.Exec(`update mt_order_car set num=num+` + num + ` where id=` + ishave[0]["id"].(string)); err != nil {
				beego.Debug(err)
				js["status"] = 0
			} else {
				js["status"] = 1
				js["num"] = models.Query(`select count(*) as num from mt_order_car where status=1 and type=0 and uid=` + c.Uid)[0]["num"]
			}
		} else {
			product := models.Query(`select a.gid,b.style,a.price,a.isvip from mt_product a left join mt_shop b on a.gid=b.id where a.id=` + pid)[0]
			var gid string
			if fmt.Sprint(product["gid"]) == "0" {
				gid = "0"
			} else {
				if fmt.Sprint(product["style"]) == "0" || fmt.Sprint(product["style"]) == "<nil>" {
					gid = "0"
				} else {
					gid = fmt.Sprint(product["gid"])
				}
			}
			price := fmt.Sprint(product["price"])
			price, gid, tid := mobile.ProductPrice(pid, c.Uid)
			pro := models.Query(`select a.id,a.barcode,b.type from mt_product a left join mt_brand b on a.bid=b.id where a.id=` + pid)[0]
			if pro["type"].(string) == "2" {
				pid = models.Query(`select id from mt_product where status=1 and censoring=1 and barcode=` + pro["barcode"].(string) + ` and id!=` + pro["id"].(string))[0]["id"].(string)
			}
			sql := fmt.Sprintf(`insert into mt_order_car (pid,gid,num,uid,price,addtime,spec,type) values (%v,%v,%v,%v,%v,'%v',%v,%v)`,
				pid, gid, num, c.Uid, price, sword.Gettimes(""), spec, tid)
			if err := models.Exec(sql); err != nil {
				beego.Debug(err)
				js["status"] = 0
			} else {
				js["status"] = 1
				js["num"] = models.Query(`select count(*) as num from mt_order_car where status=1 and type=0 and uid=` + c.Uid)[0]["num"]
			}
		}
	}
}

type ShopcarSure struct {
	BaseController
}
type ShopcarBuy struct {
	BaseController
}

func (c *ShopcarBuy) Get() {
	defer c.ServeJSON()
	var js = make(map[string]interface{})
	c.Data["json"] = &js
	num := c.GetString("num")
	pid := c.GetString("pid")
	t := c.GetString("type")
	if c.Uid == "" {
		js["status"] = 2
	} else {
		var price string
		var gid string
		var tid = "0"
		if t == "1" {
			price, gid, tid = mobile.ProductPriceA(pid, c.Uid)
		} else {
			price, gid, _ = mobile.ProductPrice(pid, c.Uid)
		}
		pro := models.Query(`select a.id,a.barcode,b.type from mt_product a left join mt_brand b on a.bid=b.id where a.id=` + pid)[0]
		if pro["type"].(string) == "2" {
			pid = models.Query(`select id from mt_product where status=1 and censoring=1 and barcode=` + pro["barcode"].(string) + ` and id!=` + pro["id"].(string))[0]["id"].(string)
		}
		sql := fmt.Sprintf(`insert into mt_order_car (pid,gid,price,num,uid,addtime,type,tid,spec) values 
			(%v,%v,%v,%v,%v,'%v','%v',%v,%v)`, pid, gid, price, num, c.Uid, sword.Gettimes(""), t, tid, c.GetString("spec"))
		if res, err := models.Orm().Raw(sql).Exec(); err != nil {
			beego.Debug(err)
			js["status"] = 0
		} else {
			js["cid"], _ = res.LastInsertId()
			js["status"] = 1
		}
	}
}

func (c *ShopcarSure) Get() {
	nowtime := sword.Gettimes("")
	carids := strings.Join(c.GetStrings("cid"), ",")
	shop := models.Query(`select a.gid,b.name,b.taxpoint from mt_order_car a left join mt_shop b on a.gid=b.id 
		where a.uid=` + c.Uid + ` and a.id in(` + carids + `) group by a.gid`)
	if shop == nil {
		return
	}
	for _, v := range shop {
		gid := v["gid"].(string)
		var tax string
		if gid == "0" {
			tax = fmt.Sprint(models.Systems()["taxpoint"])
		} else {
			tax = fmt.Sprint(v["taxpoint"])
		}
		shopcar := models.Query(`select a.id,a.num,b.title,a.type,c.pathname,a.pid,b.model,a.price,b.number,b.spec,a.gid,a.spec as spec2 from mt_order_car a 
			left join mt_product b on a.pid=b.id left join mt_resources c on b.img=c.id where a.gid=` + gid + ` and a.id in(` + carids + `)`)
		var pricesum = "0.00"
		for _, s := range shopcar {
			var pricem string
			if fmt.Sprint(s["spec2"]) == "1" {
				pricem = fmt.Sprint(s["price"])
			} else {
				pricem = sword.Mult(fmt.Sprint(s["price"]), fmt.Sprint(s["number"]))

			}
			s["pricem"] = pricem
			pricemn := sword.Mult(pricem, fmt.Sprint(s["num"]))
			pricesum = sword.Sum(pricesum, pricemn)
		}
		v["shopcar"] = shopcar
		v["pricesum"] = pricesum
		v["pricet"] = sword.Sum(pricesum, sword.Divi(sword.Mult(pricesum, tax), "100"))
		v["coupon"] = models.Query(`select b.name,a.id,b.offer,b.full from mt_member_coupon 
			a join (select * from mt_coupon where full<=` + pricesum + `
			 and starttime<='` + nowtime + `' and endtime>'` + nowtime + `' and gid=` + gid + `) b on a.yid=b.id where a.status=1`)
	}
	address := models.Query(`select a.id,a.name,a.mobile,a.address,b.name as shen,c.name as shi,d.name as qu from mt_member_address a 
			left join mt_area b on a.province=b.code left join mt_area c on a.city=c.code left join mt_area d on a.area=d.code where a.status=1 
			and a.uid=` + c.Uid + ` order by a.default desc,a.addtime desc`)
	mem := models.Query(`select money,paypassword as token,wx_openid_gzh,wx_openid_xapp,wx_openid_app from mt_member where id=` + c.Uid)[0]
	invoice := models.Query(`select look from mt_order_invoice where uid=` + c.Uid)
	c.Data["info"] = shop
	c.Data["mem"] = mem
	c.Data["address"] = address
	c.Data["invoice"] = invoice
	c.TplName = "pc/shopcar/sure.html"
}

type ShopData struct {
	Type     string  `json:"type" form:"type"`
	Password string  `json:"password" form:"password"`
	Address  string  `json:"address" form:"address"`
	Style    int     `json:"style" form:"style"`
	Shop     []Shops `json:"shop" form:"shop"`
}
type Shops struct {
	Invoice string `json:"invoice" form:"invoice"`
	Carid   string `json:"carid" form:"carid"`
	Gid     string `json:"gid" form:"gid"`
	Yid     string `json:"yid" form:"yid"`
	Content string `json:"content" form:"content"`
}

func (c *ShopcarSure) Post() {
	defer c.ServeJSON()
	var js = make(map[string]interface{})
	c.Data["json"] = &js
	var shopdata = ShopData{}
	nowtimes := sword.Gettimes("")
	var ot string
	var oids []string

	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &shopdata); err != nil {
		beego.Debug(err)
		js["status"] = 0 //解析失败
		return
	}
	js["type"] = shopdata.Type
	var moneysum = "0.00"
	var agid = "0"
	o := models.Orm()
	o.Begin()
	add := models.Query(`select * from mt_member_address where id=` + shopdata.Address)[0]
	var inv orm.Params
	if invs := models.Query(`select * from mt_order_invoice where uid=` + c.Uid); invs != nil {
		inv = invs[0]
	}
	var rinfo []map[string]interface{}
	integralbf, err := strconv.ParseFloat(fmt.Sprint(models.Systems()["integral"]), 64)
	if err != nil {
		beego.Debug(err)
		integralbf = 100
	}
	var integralsum = "0.00"
	for _, v := range shopdata.Shop {
		var pricem = "0.00"
		var moneym = "0.00"
		shopcar := models.Query(`select a.id,a.num,a.pid,a.tid,a.price,a.price as cprice,b.number,a.type,a.gid,b.isvip,a.spec from mt_order_car a left join mt_product b on a.pid=b.id 
		where a.id in(` + v.Carid + `) and a.status=1 and a.gid=` + v.Gid)
		if shopcar == nil {
			o.Rollback()
			beego.Debug("购物车数据已使用")
			js["status"] = 5
			return
		}
		for _, s := range shopcar {
			brandFold := "100"
			brand := models.Query(`select fold from mt_brand_classify
				where find_in_set(?,uid) and find_in_set(?,bid) and status=1`, c.Uid, s["bid"])
			if brand != nil {
				if brand[0]["fold"] != nil {
					brandFold = brand[0]["fold"].(string)
				}
			}
			if s["tid"] != nil {
				agid = fmt.Sprint(s["tid"])
			}
			price := fmt.Sprint(s["cprice"])
			price2 := fmt.Sprint(s["price"])
			number := fmt.Sprint(s["number"])
			num := fmt.Sprint(s["num"])
			ot = fmt.Sprint(s["type"])
			if err := models.Exec(fmt.Sprintf(`update mt_product set sellnum=sellnum+%v,inventory=abs(inventory-%v) where id=%v`, num, num, s["pid"])); err != nil {
				o.Rollback()
				beego.Debug(err)
			}
			if fmt.Sprint(s["spec"]) == "0" {
				pricem = sword.Sum(pricem, sword.Mult(price2, sword.Mult(number, num)))
				price = sword.Divi(sword.Mult(price, brandFold), "100")
				moneym = sword.Sum(moneym, sword.Mult(price, sword.Mult(number, num)))
			} else {
				pricem = sword.Sum(pricem, sword.Mult(price2, num))
				price = sword.Divi(sword.Mult(price, brandFold), "100")
				moneym = sword.Sum(moneym, sword.Mult(price, num))
			}
		}
		count := sword.Cut(pricem, moneym)
		if v.Yid != "0" {
			coupon := models.Query(`select b.offer from mt_member_coupon a left join mt_coupon b on a.yid=b.id where a.id=` + v.Yid)[0]
			c_count := fmt.Sprint(coupon["offer"])
			moneym = sword.Cut(moneym, c_count)
			if _, err := o.Raw(`update mt_member_coupon set status=0 where id=` + v.Yid).Exec(); err != nil {
				beego.Debug(err)
				o.Rollback()
				js["status"] = 0
				return
			}
		}

		var sql string

		if v.Invoice == "1" {
			var tax string
			if v.Gid == "0" {
				tax = fmt.Sprint(models.Systems()["taxpoint"])
			} else {
				tax = fmt.Sprint(models.Query(`select taxpoint from mt_shop where id=` + v.Gid))
			}
			// tax := models.Systems()["taxpoint"].(string)
			taxmoney := sword.Divi(sword.Mult(moneym, tax), "100")
			moneym = sword.Sum(moneym, taxmoney)

			sql = fmt.Sprintf(`insert into mt_order (gid,yid,uid,ordernum,carid,price,money,count,addtime,paytype,invoice,addressid,tax,taxid,
					look,bank,account,cadress,name,mobile,province,city,area,address,type,agid,content) values ('%v','%v','%v','%v','%v','%v',
					'%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v')`, v.Gid, v.Yid,
				c.Uid, GetOrdernum(), v.Carid, pricem, moneym, count, nowtimes, shopdata.Type, v.Invoice, shopdata.Address, taxmoney,
				inv["ein"], inv["look"], inv["bank"], inv["account"], inv["address"], add["name"], add["mobile"], add["province"],
				add["city"], add["area"], add["address"], ot, agid, c.GetString("content"))
		} else {
			sql = fmt.Sprintf(`insert into mt_order (gid,yid,uid,ordernum,carid,price,money,count,addtime,paytype,invoice,addressid,tax,name,mobile,
					province,city,area,address,type,agid,content) values ('%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%.2f','%v','%v'
					,'%v','%v','%v','%v','%v','%v','%v')`, v.Gid, v.Yid, c.Uid, GetOrdernum(), v.Carid, pricem, moneym, count, nowtimes, shopdata.Type,
				v.Invoice, shopdata.Address, 0.00, add["name"], add["mobile"], add["province"], add["city"], add["area"], add["address"], ot,
				agid, c.GetString("content"))
		}
		moneysum = sword.Sum(moneysum, moneym)
		var oid string
		if res, err := o.Raw(sql).Exec(); err != nil {
			beego.Debug(err)
			o.Rollback()
			js["status"] = 0
			return
		} else {
			oid64, _ := res.LastInsertId()
			oid = fmt.Sprint(oid64)
			oids = append(oids, oid)
			caridArr := strings.Split(v.Carid, ",")
			for _, v := range caridArr {
				orderCar := models.Query(`select b.bid,a.pid,a.num from mt_order_car a 
					left join mt_product b on a.pid=b.id 
					where a.id=?`, v)
				if orderCar != nil {
					brandFold := "100"
					brand := models.Query(`select fold from mt_brand_classify
						where find_in_set(?,uid) and find_in_set(?,bid) and status=1`, c.Uid, orderCar[0]["bid"])
					if brand != nil {
						if brand[0]["fold"] != nil {
							brandFold = brand[0]["fold"].(string)
						}
					}
					if _, err := o.Raw(`update mt_order_car set brandFold=`+brandFold+`,status=2,paytime='`+nowtimes+`' where id=?`, v).Exec(); err != nil {
						beego.Debug(err)
						o.Rollback()
						js["status"] = 0
						return
					} else {
						if _, err := o.Raw(`update mt_product set sellnum=sellnum+`+orderCar[0]["num"].(string)+` where id=?`, orderCar[0]["pid"]).Exec(); err != nil {
							beego.Debug(err)
							o.Rollback()
							js["status"] = 0
							return
						}
					}
				}
			}
		}
		var in = make(map[string]interface{})
		in["oid"] = oid
		in["money"] = moneym
		moneyi, _ := strconv.ParseFloat(moneym, 64)
		integral := moneyi / integralbf
		integrals := fmt.Sprintf(`%.f`, integral)
		integralsum = sword.Sum(integralsum, integrals)
		in["integral"] = integrals
		rinfo = append(rinfo, in)
	}
	//推送
	moneysumf, _ := strconv.ParseFloat(moneysum, 64)
	if shopdata.Type == "1" {
		// if shopdata.Password != "" {
		// 	paypassword := sword.ToMD5(shopdata.Password)
		// 	if ispok := models.Query(`select id from mt_member where paypassword='` + paypassword + `' and id=` + c.Uid); ispok == nil {
		// 		o.Rollback()
		// 		js["status"] = 3 //密码错误
		// 		return
		// 	}
		// }
		if ismoney := models.Query(`select uid from mt_member where id=` + c.Uid + ` and money>=` + moneysum); ismoney == nil {
			o.Rollback()
			js["status"] = 2
			return
		}
		if _, err := o.Raw(fmt.Sprintf(`update mt_member set money=money-%v where id=%v`, moneysum, c.Uid)).Exec(); err != nil {
			beego.Debug(err)
			o.Rollback()
			js["status"] = 0
			return
		}
		if _, err := o.Raw(`update mt_order set status=2,paytime='` + nowtimes + `' where id in(` + strings.Join(oids, ",") + `)`).Exec(); err != nil {
			beego.Debug(err)
			o.Rollback()
			js["status"] = 0
			return
		}
		for _, v := range rinfo {
			if _, err := o.Raw(fmt.Sprintf(`insert into mt_member_money_detail (uid,type,money,oid,addtime,paytype) values 
							('%v','%v','%v','%v','%v','%v')`, c.Uid, 3, v["money"], v["oid"], nowtimes, shopdata.Type)).Exec(); err != nil {
				beego.Debug(err)
				o.Rollback()
				js["status"] = 0
				return
			}
		}
		integral, _ := strconv.ParseFloat(integralsum, 64)
		if _, err := o.Raw(fmt.Sprintf(`update mt_member set integral=integral+%.f where id=%v`, integral, c.Uid)).Exec(); err != nil {
			beego.Debug(err)
			o.Rollback()
			js["status"] = 0
			return
		}
		for _, v := range rinfo {
			if _, err := o.Raw(fmt.Sprintf(`insert into mt_member_integral (uid,type,number,oid,addtime) values 
							('%v','%v','%v','%v','%v')`, c.Uid, 0, v["integral"], v["oid"], nowtimes)).Exec(); err != nil {
				beego.Debug(err)
				o.Rollback()
				js["status"] = 0
				return
			}
		}
		o.Commit()
		js["status"] = 1
		mem := models.Query(`select wx_openid_gzh,monicker from mt_member where id=` + c.Uid)[0]
		uopenid := fmt.Sprint(mem["wx_openid_gzh"])
		order := models.Query(`select a.carid,a.gid,a.money from mt_order a where a.id in(` + strings.Join(oids, ",") + `)`)
		for _, v := range order {
			var pnames []string
			pna := models.Query(`select a.num,b.title from mt_order_car a left join mt_product b on a.pid=b.id where a.id in(` + v["carid"].(string) + `)`)
			for _, p := range pna {
				pnames = append(pnames, fmt.Sprintf(`%v X %v`, p["title"], p["num"]))
			}
			gid := v["gid"].(string)
			var g orm.Params
			if gid == "0" {
				g = models.Query(`select a.name from mt_systems a left join mt_member b on a.uid=b.id`)[0]
			} else {
				g = models.Query(`select a.name from mt_shop a left join mt_member b on a.uid=b.id`)[0]
			}
			gname := g["name"].(string)
			data := map[string]map[string]interface{}{
				"first":    {"value": fmt.Sprintf(`您在 %v 下单成功`, gname)},
				"keyword1": {"value": strings.Join(pnames, `、`), "color": `#36353A`},
				"keyword2": {"value": v["money"].(string), "color": `#e31939`},
				"keyword3": {"value": nowtimes, "color": "#9c9c9c"},
				"remark":   {"value": `您已下单成功,请尽快付款`},
			}
			models.Push(uopenid, `Ckvj_9CBCLYGsN5vngxt8f5vcp8VHDIaEWWsNJbVqGI`, data, models.Urlc+"/mobile/my/order", "")
		}
		mobile.PayPush(strings.Join(oids, ","))
	} else if shopdata.Type == "2" {
		res := mobile.WxPay(c.Uid, "支付订单", c.Ctx.Input.IP(), strings.Join(oids, ","), moneysumf, 3, 0)
		if res != nil {
			o.Commit()
			js["res"] = res
			js["oid"] = strings.Join(oids, ",")
		} else {
			o.Rollback()
			js["status"] = 0
			return
		}
	} else if shopdata.Type == "3" {
		if res, err := mobile.Alipay(c.Uid, moneysumf, strings.Join(oids, ","), 0, 3); err != nil {
			beego.Debug(err)
			o.Rollback()
			js["status"] = 0
			return
		} else {
			o.Commit()
			js["res"] = res
		}
	}

}

type ONN struct {
	Times string `json:"times"`
	Num   int    `json:"num"`
}

func GetOrdernum() string {
	var retu = ONN{}
	bytes, err := ioutil.ReadFile("order/ordernum.json")
	if err != nil {
		beego.Debug("ReadFile: ", err)
	}
	var xxx = ONN{}
	if err := json.Unmarshal(bytes, &xxx); err != nil {
		beego.Debug("Unmarshal: ", err)
	}
	timestamp1 := time.Now().Format("2006-01-02")
	timestamp2 := xxx.Times
	if timestamp1 == timestamp2 {
		retu.Num = xxx.Num + 1
	} else {
		retu.Num = 1
	}
	retu.Times = timestamp1
	arr2, _ := json.Marshal(retu)
	if writeerr := ioutil.WriteFile("order/ordernum.json", arr2, 0777); writeerr != nil {
		beego.Debug(writeerr)
	}
	now := time.Now()
	year := now.Year()
	month := int(now.Month())
	day := now.Day()
	var ordernum string
	ordernum = fmt.Sprint(year)
	if month < 10 {
		ordernum += fmt.Sprintf(`0%v`, month)
	} else {
		ordernum += fmt.Sprint(month)
	}
	if day < 10 {
		ordernum += fmt.Sprintf(`0%v`, day)
	} else {
		ordernum += fmt.Sprint(day)
	}
	num := retu.Num
	nums := fmt.Sprint(num)
	switch len(nums) {
	case 1:
		ordernum += fmt.Sprintf(`00%v`, nums)
	case 2:
		ordernum += fmt.Sprintf(`0%v`, nums)
	case 3:
		ordernum += fmt.Sprintf(`%v`, nums)
		// case 4:
		// 	ordernum += fmt.Sprintf(`0000%v`, nums)
		// case 5:
		// 	ordernum += fmt.Sprintf(`000%v`, nums)
		// case 6:
		// 	ordernum += fmt.Sprintf(`00%v`, nums)
		// case 7:
		// 	ordernum += fmt.Sprintf(`0%v`, nums)
		// case 8:
		// 	ordernum += fmt.Sprintf(`%v`, nums)
	}
	return ordernum
}

type ShopcarChangenum struct {
	BaseController
}

func (c *ShopcarChangenum) Get() {
	defer c.ServeJSON()
	id := c.GetString("id")
	if istrue := models.Query(`select id,num,pid from mt_order_car where uid=` + c.Uid + ` and id=` + id); istrue != nil {
		oldnum, _ := strconv.Atoi(fmt.Sprint(istrue[0]["num"]))
		num, _ := c.GetInt("num")
		if num > oldnum {
			enough := models.Query(`select id from mt_product where id=? and inventory>=?`, istrue[0]["pid"], num-oldnum)
			if enough == nil {
				c.Data["json"] = 3
				return
			}
		}

		if err := models.Exec(`update mt_order_car set num=? where id=?`, num, id); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
		} else {
			c.Data["json"] = 1
		}
	} else {
		c.StopRun()
	}
}

type Test struct {
	BaseController
}

func (c *Test) Get() {
	c.EnableRender = false
	shen := models.Query(`select id,code,name from mt_area where pid=0`)
	for _, v := range shen {
		shi := models.Query(`select id,code,name from mt_area where pid=` + v["id"].(string))
		for _, s := range shi {
			s["qu"] = models.Query(`select id,code,name from mt_area where pid=` + s["id"].(string))
		}
		v["shi"] = shi
	}
	shi2, _ := json.Marshal(shen)
	if writeerr := ioutil.WriteFile("token/area.json", shi2, 0777); writeerr != nil {
		beego.Debug(writeerr)
	}
}

type ShopcarOrdercheck struct {
	BaseController
}

func (c *ShopcarOrdercheck) Get() {
	defer c.ServeJSON()
	oid := c.GetString("oid")
	if is := models.Query(`select id from mt_order where status>1 and id in(` + oid + `)`); is != nil {
		c.Data["json"] = 1
	} else {
		c.Data["json"] = 0
	}
}

type ShopcarExcel struct {
	beego.Controller
}

func (c *ShopcarExcel) Get() {
	id := c.GetString("id")
	xlsx := excelize.NewFile()
	// index := xlsx.NewSheet("Sheet1")

	xlsx.SetCellValue("Sheet1", "A1", "产品名称")
	xlsx.SetCellValue("Sheet1", "B1", "条形码")
	xlsx.SetCellValue("Sheet1", "C1", "产品型号")
	xlsx.SetCellValue("Sheet1", "D1", "装箱数")
	xlsx.SetCellValue("Sheet1", "E1", "体积(立方)")
	xlsx.SetCellValue("Sheet1", "F1", "重量(kg)")
	xlsx.SetCellValue("Sheet1", "G1", "数量")
	xlsx.SetCellValue("Sheet1", "H1", "单价")
	xlsx.SetCellValue("Sheet1", "I1", "总价")
	xlsx.SetCellValue("Sheet1", "J1", "图片")
	shopcar := models.Query(`select a.gid,a.pid,a.num,a.sendnum,a.status,b.title,b.spec,b.number,b.barcode,a.price,c.pathname,b.model,a.spec as spec2,b.width,b.length,b.height,b.weight  
			from mt_order_car a 
			left join mt_product b on a.pid=b.id 
			left join mt_resources c on b.img=c.id 
			where a.uid=? and a.status=1 and a.type<>1`, id)

	for k, v := range shopcar {
		k += 2
		xlsx.SetCellValue("Sheet1", "H"+fmt.Sprint(k), v["price"])
		if fmt.Sprint(v["spec2"]) == "0" {
			v["price"] = sword.Mult(v["price"].(string), v["number"].(string))
		}
		width := fmt.Sprint(v["width"])
		length := fmt.Sprint(v["length"])
		height := fmt.Sprint(v["height"])
		weight := fmt.Sprint(v["weight"])
		number := fmt.Sprint(v["number"])
		num := fmt.Sprint(v["num"])

		tjone := sword.Divi(sword.Mult(width, sword.Mult(height, sword.Mult(length, num))), "1000000")
		zlone := sword.Divi(sword.Mult(sword.Mult(weight, number), num), "1000")
		xlsx.SetCellValue("Sheet1", "A"+fmt.Sprint(k), v["title"])
		xlsx.SetCellValue("Sheet1", "B"+fmt.Sprint(k), v["barcode"])
		xlsx.SetCellValue("Sheet1", "C"+fmt.Sprint(k), v["model"])
		xlsx.SetCellValue("Sheet1", "D"+fmt.Sprint(k), v["number"])
		xlsx.SetCellValue("Sheet1", "E"+fmt.Sprint(k), tjone)
		xlsx.SetCellValue("Sheet1", "F"+fmt.Sprint(k), zlone)
		xlsx.SetCellValue("Sheet1", "G"+fmt.Sprint(k), num)
		xlsx.SetCellValue("Sheet1", "I"+fmt.Sprint(k), sword.Mult(num, fmt.Sprint(v["price"])))

		pathname := fmt.Sprint(v["pathname"])
		pathname = strings.Replace(pathname, "https://tcsc.oss-cn-hangzhou.aliyuncs.com/", "", -1)
		pathname = strings.Replace(pathname, "?x-oss-process=style/base", "", -1)
		pathnameArr := strings.Split(pathname, ".")
		ext := strings.ToLower(path.Ext(pathname))
		pathname = pathnameArr[0] + ext
		if pathname != "" && pathname != "<nil>" {
			err := xlsx.AddPicture("Sheet1", fmt.Sprintf("J%v", k), pathname, `{"lock_aspect_ratio":false,"locked":true,"print_obj":true,"x_scale":0.2,"y_scale":0.2}`)
			if err != nil {
				beego.Debug(err)
			}
		}
	}

	// nowtimes := fmt.Sprint(time.Now().Unix())
	err := os.MkdirAll("static/xlsx", 0777)
	if err != nil {
		beego.Debug(err)
		return
	}

	err = xlsx.SaveAs("static/xlsx/" + id + ".xlsx")
	if err != nil {
		beego.Debug(err)
		return
	}
	c.Ctx.Redirect(302, "/static/xlsx/"+id+".xlsx")
}
